<template>
  <div>
    <el-tree
      :data="categoryTree"
      :props="defaultProps"
      :highlight-current="true"
      node-key="_id"
      default-expand-all
      :expand-on-click-node="false"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <span>{{ node.label }}</span>
        <span class="el-buton-group">
          <el-button
            size="mini"
            plain
            type="primary"
            @click="() => edit(node, data)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            plain
            type="danger"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
  </div>

</template>
<script>
import { list, del } from '@/api/category'
export default {
  data() {
    return {
      categoryTree: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  created: function() {
    this.loadCategory()
  },
  methods: {
    loadCategory: function() {
      list().then(response => {
        this.categoryObjects = response.data
        // 递归
        var tree = require('../../utils/utils').tree
        this.categoryTree = tree(this.categoryObjects, '')
      })
    },
    edit: function(store, data) {
      this.$router.push({
        name: 'categoryAdd',
        query: {
          _id: data._id
        }
      })
    },
    remove(store, data) {
      console.log(data)
      console.log(store)
      this.$confirm('确认删除分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 判断有没有子分类
        if (data.children) {
          this.$message.error('请先删除子分类')
        }
        // 请求网络删除分类
        del(data).then(response => {
          // store.remove(data);
          this.loadCategory()
          this.$message({
            type: 'success',
            message: response.msg
          })
        })
      },
      () => {
        console.log('操作取消')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.el-tree >>> .el-tree-node__content {
  // height: 100px;
  margin-top: 5px;
  margin-bottom: 5px;
}
</style>
